// @ts-ignore
import { getUserInfo } from '../../../http/api/userServiceApi'
import { getOrderById, ReOrderSet2 } from '../../../http/api/orderService'
import Toast from 'tdesign-miniprogram/toast/index'

let moment = require('../../../utils/moment')
let amapFile = require('../../../lib/amap-wx.130')
// @ts-ignore
let config = require('../../../lib/config')
Page({
    /**
     * 页面的初始数据
     */
    data: {
        configPage: config,
        orderInfo: {}, // 订单信息
        driverInfo: {}, // 司机信息
        userInfo: {}, //客户信息
        // 经度
        longitude: 0,
        // 纬度
        latitude: 0,
        name: '',
        // 标签
        markers: [
            { id: 0, latitude: 0, longitude: 0, width: 34, height: 34 },
            { id: 1, latitude: 0, longitude: 0, width: 34, height: 34 },
            { id: 2, latitude: 0, longitude: 0, width: 34, height: 34 },
            { id: 3, latitude: 0, longitude: 0, width: 34, height: 34 }
        ],
        //	是否 未抢单(显示 抢单)0 已抢单(显示 已取货)1 已取货(显示 已送达)2
        orderStatus: 0,
        mm: -1,
        userId: '',
        ref: null
    } as any,

    call(e: any) {
        console.log(e.currentTarget.dataset.phone)
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone //仅为示例，并非真实的电话号码
        })
    },

    find() {
        wx.openLocation({
            latitude: Number(this.data.orderInfo.end_lat), //维度
            longitude: Number(this.data.orderInfo.end_lng), //经度
            name: this.data.orderInfo.end_address, //目的地定位名称
            scale: 15 //缩放比例
        })
    },
    /**
     * 抢单
     */
    grabAnOrder(e: any) {
        const orderInfo = e.currentTarget.dataset.orderinfo
        this.setData({
            orderStatus: 1
        })
        this.setTheStartingPointAndEndPoint(orderInfo.start_lng, orderInfo.start_lat, orderInfo.end_lng, orderInfo.end_lat)
    },

    /**
     * 已取货
     * @param orderInfo 订单信息
     */
    async receivedGoods(e) {
        this.setData({
            orderStatus: 2
        })
        let data = {
            driver_order: this.data.orderInfo.driver_order_id,
            local: this.data.longitude + ',' + this.data.latitude,
            user_openid: wx.getStorageSync('openid'),
            driver_code: e.currentTarget.dataset.index,
            local_string: this.data.name
        }
        console.log(data)
        if (this.data.orderInfo.order_type == 1 || this.data.orderInfo.order_type == 2) {
            this.TFLatLng(this.data.orderInfo.start_lat, this.data.orderInfo.start_lng, data)
        } else {
            this.TFLatLng(this.data.orderInfo.end_lat, this.data.orderInfo.end_lng, data)
        }
    },

    /**
     * 设置起点终点
     * @param start_lng
     * @param start_lat
     * @param terminalLongitude 终点经度
     * @param terminalLatitude 终点纬度
     */
    setTheStartingPointAndEndPoint(start_lng: string, start_lat: string, end_lng: string, end_lat: string) {
        let that = this
        let myAmapFun = new amapFile.AMapWX({
            key: config.Config.key
        })
        //获取自己所在地址的定位
        myAmapFun.getRegeo({
            success: function (data: any) {
                //成功回调
                console.log(data, '---获取自己所在地址的定位')
                const { longitude, latitude, name } = data[0]
                const { markers } = that.data
                markers[0] = {
                    iconPath: '../../../assets/marker/终点.png',
                    id: 0,
                    latitude: end_lat,
                    longitude: end_lng,
                    width: 34,
                    height: 34
                }
                markers[1] = {
                    iconPath: '../../../assets/marker/起点.png',
                    id: 1,
                    latitude: start_lat,
                    longitude: start_lng,
                    width: 34,
                    height: 34
                }
                that.setData({
                    longitude: longitude,
                    latitude: latitude,
                    name: name,
                    markers: markers
                })
                return data
            },
            fail: function (info: any) {
                //失败回调
                console.log(info)
            }
        })
    },
    rad(d) {
        return (d * Math.PI) / 180.0
    },

    // 根据经纬度计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
    getDistances(lat1, lng1, lat2, lng2) {
        var radLat1 = this.rad(lat1)
        var radLat2 = this.rad(lat2)
        var a = radLat1 - radLat2
        var b = this.rad(lng1) - this.rad(lng2)
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
        s = s * 6378.137 // EARTH_RADIUS;
        // 输出为公里
        s = Math.round(s * 10000) / 10000

        var distance = s
        var distance_str = ''

        if (parseInt(distance) >= 1) {
            // distance_str = distance.toFixed(1) + "km";
            distance_str = distance.toFixed(2) + 'km'
        } else {
            // distance_str = distance * 1000 + "m";
            distance_str = (distance * 1000).toFixed(2) + 'm'
        }

        //s=s.toFixed(4);
        // console.info('距离是', s);
        // console.info('距离是', distance_str);
        // return s;
        //小小修改，这里返回对象
        let objData = {
            distance: distance,
            distance_str: distance_str
        }
        return objData
    },
    /**
     * 判断自身位置到点位置距离 500m
     * @param option
     */
    TFLatLng(lat, lng, body) {
        //获取自己所在地址的定位
        let tis = this
        let myAmapFun = new amapFile.AMapWX({
            key: config.Config.key
        })
        myAmapFun.getRegeo({
            success: async function (data) {
                //成功回调
                console.log(data, '---获取自己所在地址的定位')
                console.log(data[0].latitude, data[0].longitude, lat, lng)
                let mm = tis.getDistances(data[0].latitude, data[0].longitude, lat, lng)
                if (mm.distance > 1) {
                    Toast({
                        context: tis,
                        selector: '#t-toast',
                        message: '距离目标地点过远',
                        theme: 'error',
                        direction: 'column'
                    })
                } else {
                    let res: any = await ReOrderSet2(body)
                    console.log(res)
                    if (res.data.msg == '操作成功') {
                        let info = tis.data.orderInfo
                        info.order_type = info.order_type + 1
                        tis.fasong()
                        tis.setData({
                            orderInfo: info
                        })
                    }
                }
            }
        })
    },
    //生成唯一不重复ID
    generateUuid: function () {
        // 生成随机数
        const randomNum = Math.floor(Math.random() * 1000000)

        // 获取当前时间戳
        const timestamp = Date.now()

        // 拼接随机数和时间戳
        return randomNum + timestamp
    },
    setOwnerLocation() {
        let that = this
        let myAmapFun = new amapFile.AMapWX({ key: config.Config.key })
        //获取自己所在地址的定位
        myAmapFun.getRegeo({
            success: function (data: any) {
                //成功回调
                console.log(data, 'getRegeo')
                const { longitude, latitude, name } = data[0]
                const { markers, driverInfo } = that.data

                markers[2] = {
                    iconPath: driverInfo.user_icon,
                    id: 2,
                    latitude,
                    longitude,
                    width: 32,
                    height: 32
                }
                that.setData({
                    longitude,
                    latitude,
                    location: name,
                    markers: markers
                })
            },
            fail: function (info: any) {
                //失败回调
                console.log(info)
            }
        })
    },

    async connect() {
        console.log(wx.getStorageSync('isConnectWS'), "---wx.getStorageSync('isConnectWS')")
        if (!wx.getStorageSync('isConnectWS')) {
            await wx.connectSocket({
                url: 'wss://api.myscw.top:8085/'
            })
            wx.setStorageSync('isConnectWS', true)
        } else {
            console.warn('已存在ws连接')
        }
    },

    login(userId: any, orderId: any) {
        const that = this
        // 注册
        wx.sendSocketMessage({
            data: JSON.stringify({
                type: 'login',
                login_type: 'driver',
                user: userId,
                order_id: orderId
            }), //这里根据后台的格式发送数据，好像这个需要转换成字符串。
            success: (res: any) => {
                console.log({
                    type: 'login',
                    login_type: 'driver',
                    user: userId,
                    order_id: orderId
                })
                console.log('消息发送成功,登录成功', res)
            },
            fail: res => {
                console.log('消息发送失败,登录失败', res)
                that.reconnect(userId, orderId)
            }
        })
    },
    async reconnect(userId: string, orderId: string) {
        await wx.removeStorageSync('isConnectWS')
        setTimeout(async () => {
            // 连接ws
            await this.connect()
            // 打开连接
            await this.openConnect()
            await this.login(userId, orderId)
        }, 2000)
    },
    async openConnect() {
        let tis = this
        await wx.onSocketOpen(function (res: any) {
            console.log(res, 'WebSocket连接已打开！')
            tis.setData({
                ref: setInterval(function () {
                    tis.fasong()
                }, 50000)
            })
        })
    },
    async getMessage() {
        let that = this
        await wx.onSocketMessage(async function (res: any) {
            let resValue = JSON.parse(res.data)
            console.log('服务器发送的消息：', resValue)
            if (that.data.orderInfo.order_type == 4 || that.data.orderInfo.order_type == 5) {
                console.log('订单完成')
                // 关闭ws连接
                wx.closeSocket()
                wx.removeStorageSync('isConnectWS')
                wx.removeStorageSync('userWsID')
            }
            that.setData({
                orderType: config.Config.ORDER_MAP[that.data.orderInfo.order_type]
            })
        })
        wx.onSocketError(function (err) {
            console.error('WebSocket 连接出错', err)

            that.reconnect(that.createUser(), that.data.orderInfo.ID)
        })
        wx.onSocketClose(function (res) {
            console.log('WebSocket 连接已关闭', res)
            that.setData({
                ref: null
            })
            // 在这里可以处理连接关闭后的逻辑
        })
    },
    sendMessage() {},
    createUser() {
        if (!wx.getStorageSync('userWsID')) {
            const id = `driver_${this.generateUuid()}`
            wx.setStorageSync('userWsID', id)
            return id
        } else {
            return wx.getStorageSync('userWsID')
        }
    },
    async fasong() {
        const tis = this
        if (!wx.getStorageSync('openLocationBackground')) {
            wx.authorize({
                scope: 'scope.userLocationBackground',
                success: async (res: any) => {
                    console.log('有权限', res)
                    await wx.startLocationUpdateBackground({
                        success: (res: any) => {
                            console.log('获取位置成功', res)
                            wx.setStorageSync('openLocationBackground', true)
                            wx.onLocationChange(async data => {
                                console.log(data)
                                const { latitude, longitude } = data
                                const { markers, driverInfo } = tis.data
                                markers[2] = {
                                    iconPath: driverInfo.user_icon,
                                    id: 2,
                                    latitude,
                                    longitude,
                                    width: 32,
                                    height: 32
                                }
                                tis.setData({
                                    longitude,
                                    latitude,
                                    location: '',
                                    markers: markers
                                })
                                console.log(tis.data.orderInfo)
                                console.log(
                                    {
                                        //
                                        type: 'User_Route_Log_Add',
                                        login_type: 'driver',
                                        user: tis.data.userId,
                                        order_id: tis.data.orderInfo.order_id,
                                        lat: latitude,
                                        lng: longitude,
                                        address: tis.data.name,
                                        order_type: tis.data.orderInfo.order_type
                                    },
                                    '----User_Route_Log_Add'
                                )
                                wx.sendSocketMessage({
                                    data: JSON.stringify({
                                        //
                                        type: 'User_Route_Log_Add',
                                        login_type: 'driver',
                                        user: tis.data.userId,
                                        order_id: tis.data.orderInfo.order_id,
                                        lat: latitude,
                                        lng: longitude,
                                        address: tis.data.name,
                                        order_type: tis.data.orderInfo.order_type
                                    }), //这里根据后台的格式发送数据，好像这个需要转换成字符串。
                                    success: res => {
                                        console.log('消息发送成功', res)
                                    },
                                    fail: res => {
                                        console.log('消息发送失败', res)
                                    }
                                })
                            })
                        },
                        fail: (res: any) => {
                            console.log(res, '----没有权限')
                        }
                    })
                },
                fail: (res: any) => {
                    console.log(res, '----没有权限')
                }
            })
        } else {
            console.warn('已开启后台定位!')
            await wx.startLocationUpdateBackground({
                success: (res: any) => {
                    console.log('获取位置成功', res)
                    wx.setStorageSync('openLocationBackground', true)
                    wx.onLocationChange(async data => {
                        console.log(data)
                        const { latitude, longitude } = data
                        const { markers, driverInfo } = tis.data
                        markers[2] = {
                            iconPath: driverInfo.user_icon,
                            id: 2,
                            latitude,
                            longitude,
                            width: 32,
                            height: 32
                        }
                        tis.setData({
                            longitude,
                            latitude,
                            location: '',
                            markers: markers
                        })
                        console.log(tis.data.orderInfo)
                        console.log(
                            {
                                //
                                type: 'User_Route_Log_Add',
                                login_type: 'driver',
                                user: tis.data.userId,
                                order_id: tis.data.orderInfo.order_id,
                                lat: latitude,
                                lng: longitude,
                                address: tis.data.name,
                                order_type: tis.data.orderInfo.order_type
                            },
                            '----User_Route_Log_Add'
                        )
                        wx.sendSocketMessage({
                            data: JSON.stringify({
                                //
                                type: 'User_Route_Log_Add',
                                login_type: 'driver',
                                user: tis.data.userId,
                                order_id: tis.data.orderInfo.order_id,
                                lat: latitude,
                                lng: longitude,
                                address: tis.data.name,
                                order_type: tis.data.orderInfo.order_type
                            }), //这里根据后台的格式发送数据，好像这个需要转换成字符串。
                            success: res => {
                                console.log('消息发送成功', res)
                            },
                            fail: res => {
                                console.log('消息发送失败', res)
                            }
                        })
                    })
                },
                fail: (res: any) => {
                    console.log(res, '----没有权限')
                }
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(option: any) {
        let that = this
        const { orderStatus, info } = option
        const orderInfo = JSON.parse(info)
        console.log(orderStatus, orderInfo)
        const res: any = await getUserInfo()
        const userInfo = res.data.data[0]
        console.log(userInfo, orderInfo, '---司机信息')
        const orderId = orderInfo.order_id
        this.setData({
            orderStatus,

            driverInfo: userInfo
        })
        // 设置用户当前位置
        await that.setOwnerLocation()
        const userId = this.createUser()

        this.setData({
            orderInfo: {
                ...orderInfo,
                get_time: moment.formatTime(orderInfo.get_time),
                arrive_go_time: moment.formatTime(orderInfo.arrive_go_time),
                arrive_end_time: moment.formatTime(orderInfo.arrive_end_time)
            },
            orderType: config.Config.ORDER_MAP[orderInfo.order_type],
            userId: userId
        })
        if (orderInfo.order_type !== 4 || orderInfo.order_type !== 5) {
            console.log(orderInfo, orderId, userId, '---orderInfo')
            this.setTheStartingPointAndEndPoint(orderInfo.start_lng, orderInfo.start_lat, orderInfo.end_lng, orderInfo.end_lat)

            // 连接ws
            await this.connect()
            // 打开连接
            await this.openConnect()
            setTimeout(async () => {
                // 登录
                await this.login(userId, this.data.orderInfo.order_id)
                // 获取消息
                await this.getMessage()
                await this.fasong()
            }, 1000)
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    onUnload() {
        // wx.closeSocket()
        wx.onSocketClose(function (res: any) {
            console.log(res, 'WebSocket连接已关闭！')
        })
    }
})
